﻿using AntMovement.Core.Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace AntMovement.SDK.LTSMC.Domain.Update
{
    public class HardwareUpdateAxis : AntMovement.Core.IHardwareUpdate
    {
        private Axis _axis;

        private ulong _nCardNo;
        private ulong _axisNo;

        public HardwareUpdateAxis(ulong nCardNo, ulong axisNo, Axis axis)
        {
            _nCardNo = nCardNo;
            _axisNo = axisNo;
            _axis = axis;
        }

        public string Update()
        {
            short error = LTSMC.smc_check_done(_axis.CardNo, _axis.AxisID);
            _axis.Status.SportStatus = error == 0;
            uint status = LTSMC.smc_axis_io_status(_axis.CardNo, _axis.AxisID);
            _axis.Status.Alm = (status & 0x0001) == 0x0001;
            _axis.Status.El_Left = (status & 0x0002) == 0x0002;
            _axis.Status.El_Right = (status & 0x0004) == 0x0004;
            _axis.Status.EMG = (status & 0x0008) == 0x0008;
            _axis.Status.ORG = (status & 0x0010) == 0x0010;
            _axis.Status.SL_Left = (status & 0x0020) == 0x0020;
            _axis.Status.SL_Right = (status & 0x0040) == 0x0040;
            _axis.Status.INP = (status & 0x0080) == 0x0080;
            _axis.Status.EZ = (status & 0x0100) == 0x0100;
            double pos = 0;
            error = LTSMC.smc_get_position_unit(_axis.CardNo, _axis.AxisID, ref pos);
            if (error != 0)
            {
                return $"CardNo[{_nCardNo}] Index[{_axis.AxisID}] smc_get_position_unit：{error}";
            }
            _axis.Status.CurrentPostion = (long)pos;
            error = LTSMC.smc_get_encoder_unit(_axis.CardNo, _axis.AxisID, ref pos);
            if (error != 0)
            {
                return $"CardNo[{_nCardNo}] Index[{_axis.AxisID}] smc_get_encoder_unit：{error}";
            }
            short enable = LTSMC.smc_read_sevon_pin(_axis.CardNo, _axis.AxisID);
            _axis.Status.Enable = enable == 0;
            _axis.Status.EqPostion = (long)pos;

            if (_axis.UnitConversion.EnableGearbox)
            {
                if (_axis.UnitConversion.EnableRotationMode)
                {
                    //旋转模式

                }
                else
                {
                    //线性模式
                    double pe = (_axis.UnitConversion.CyclePulse * _axis.UnitConversion.MotorGearRatio) / (_axis.UnitConversion.WeeklyItinerary * _axis.UnitConversion.WorkingGearRatio);
                    _axis.UnitConversion.ActualPosition = pe / (double)_axis.Status.CurrentPostion;
                }
            }
            else
            {
                double pe = _axis.UnitConversion.WeeklyItinerary / _axis.UnitConversion.CyclePulse;
                _axis.UnitConversion.ActualPosition = pe * (double)_axis.Status.CurrentPostion;
            }
            return "ok";
        }
    }
}
